#include "opencl_tools.h"

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>

//~ int mpi_rank=0, mpi_size=1;
int value;
char clPlatformName[10240];

void opencl_init(){
	
	FILE *fp;
    char *source_str;
    size_t source_size;
    fp = fopen("kernel_functions.c", "r");
    if (!fp) {
        fprintf(stderr, "Failed to load kernel.\n");
        exit(1);
    }
    source_str = (char*)malloc(MAX_SOURCE_SIZE);
    source_size = fread( source_str, 1, MAX_SOURCE_SIZE, fp);
    fclose( fp );
    // Get platform and device information
    cl_platform_id platform_id = NULL;
    cl_device_id device_id = NULL;   
    cl_uint ret_num_devices;
    cl_uint ret_num_platforms;
    cl_int ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms);
    ret = clGetDeviceIDs( platform_id, CL_DEVICE_TYPE_ALL, 1, 
            &device_id, &ret_num_devices);
	if(ret!=CL_SUCCESS){
		printf("\nError Device ID");
		exit(1);
	}
	// Get platform info
	cl_int platformInfo=clGetPlatformInfo (	platform_id,  CL_PLATFORM_NAME,  10240,  clPlatformName,  NULL);
	printf("\n\nPlatform Name=%s\n\n",clPlatformName);
    // Create an OpenCL context
    cl_context context = clCreateContext( NULL, 1, &device_id, NULL, NULL, &ret);

    // Create a command queue
    cl_command_queue command_queue = clCreateCommandQueue(context, device_id, 0, &ret);
}
void messagecl(char *fmt, ...){
    va_list argp;
    char buffer[1024];

    va_start(argp, fmt);
    vsnprintf(buffer, 1024, fmt, argp);
    va_end(argp);

    fprintf(stdout, "openCL > %s \n", buffer);
}

double getTime(){
	clock_t start;
	start = clock();
	//~ printf("start open tools=%f",start/(double)CLOCKS_PER_SEC);
	return start/(double)CLOCKS_PER_SEC;
}

void *secure_malloc_cl(size_t size){
    void *ptr;

    ptr = malloc(size);
    if( ptr == NULL )
        die_cl("Unable to allocate memory");

    return ptr;
}
void die_cl(char *fmt, ...){
    va_list argp;
    char buffer[1024];

    va_start(argp, fmt);
    vsnprintf(buffer, 1024, fmt, argp);
    va_end(argp);

    fprintf(stdout, "OpenCL_fatal ! > %s \n", buffer);
    exit(1);
}
